package com.sample.model
{
	import com.sample.Constants;
	import com.sample.command.EntityCommands;
	import com.sample.vo.ProjectVO;
	import com.sample.vo.RoleVO;
	import com.sample.vo.TypeVO;
	import com.sample.vo.UserVO;
	import com.trg.flex.ModelCache;
	import com.trg.flex.PropertyFilter;
	
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ICollectionView;
	import mx.collections.ListCollectionView;
	import mx.collections.Sort;
	import mx.collections.SortField;
	
	[Bindable]
	public class ModelLocator extends EventDispatcher
	{
		public function ModelLocator()
		{
			if (instance != null) throw new Error("Only one instance of ModelLocator can exist. User ModelLocator.getInstance()");
		}
		
		private static var instance:ModelLocator;
		
		public static function getInstance():ModelLocator {
			if (instance == null) {
				instance = new ModelLocator();
			}
			return instance;
		}
		
		public var cache:ModelCache = new ModelCache();
		
		private var _typesByCategory:Dictionary = new Dictionary(true);
		
		public function getTypesByCategory(category:String):ICollectionView {
			if (typeof _typesByCategory[category] == 'undefined') {
				var list:ListCollectionView = new ListCollectionView(cache.getAll(TypeVO));
				list.filterFunction = (new PropertyFilter("category", category)).equal;
				list.sort = new Sort();
				list.sort.fields = [new SortField("name", true)];
				list.refresh();
				_typesByCategory[category] = list;
			}
			return _typesByCategory[category];
		}
		
		public function get projects():ArrayCollection {
			return cache.getAll(ProjectVO);
		}
		
		public function get users():ArrayCollection {
			return cache.getAll(UserVO);
		}
		
		private var _roles:ArrayCollection;
		public function get roles():ArrayCollection {
			if (_roles == null) {
				_roles = EntityCommands.i.fetchAllLazy(RoleVO);
			}
			return _roles;
		}
		
		//Session user variables
		//The user that is currently logged in (if any)
		public var currentUser:UserVO = null;
		//The current state of the user session (logged in, suspended, logged out)
		public var sessionState:int = Constants.SESSION_STATE_UNKNOWN;
		
	}
}